﻿using System.Collections.Generic;
using System.Text.RegularExpressions;
using RuTracker.Interface;
using RuTracker.Interface.Editors;
using RuTrackerLib.ServiceAttibutes;

namespace RuTrackerLib.Editors
{
    [PerApplicationService]
    public class RegularExpressionEditor : IHtmlEditor
    {
        private readonly IModificationsRepository _repository;
        public RegularExpressionEditor(IModificationsRepository repository)
        {
            _repository = repository;
        }

        public string Edit(string html)
        {
            IList<Modification> modifications = _repository.LoadModifications();
            string str = html;
            foreach (Modification modification in modifications)
            {
                Regex regex = new Regex(modification.Regex);
                if (!regex.IsMatch(str))
                    Log.Warn("Regular expression modification cannot be applied. Modification index: {0}", modification.Id);
                str = regex.Replace(str, modification.ReplaceWith ?? string.Empty);
            }

            return str;
        }
    }
}
